package com.thirdguardian.sign.signv4;

import cn.hutool.core.util.StrUtil;
import com.thirdguardian.sign.comm.CommUtils;
import com.thirdguardian.sign.comm.ConstStr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SignKit {

    /**
     * 构造签名串
     *
     * @param url       请求接口 /v3/certificates
     * @param timestamp 获取发起请求时的系统当前时间戳
     * @param nonceStr  随机字符串
     * @param body      请求报文主体
     * @return 待签名字符串
     */
    public static String buildSignMessage(String appId, String url, String timestamp, String nonceStr, String body) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(appId);
        arrayList.add(url);
        arrayList.add(timestamp);
        arrayList.add(nonceStr);
        arrayList.add(body);
        return buildSignMessage(arrayList);
    }


    /**
     * 构造签名串
     *
     * @param signMessage 待签名的参数
     * @return 构造后带待签名串
     */
    public static String buildSignMessage(ArrayList<String> signMessage) {
        if (signMessage == null || signMessage.size() <= 0) {
            return null;
        }
        StringBuilder sbf = new StringBuilder();
        for (String str : signMessage) {
            sbf.append(str).append("\n");
        }
        return sbf.toString();
    }

    /**
     * v4 接口创建签名
     *
     * @param signMessage 待签名的参数
     * @param secretKey   商户私钥
     * @return 生成 v4 签名
     */
    public static String createSign(String signMessage, String secretKey) {
        if (StrUtil.isEmpty(signMessage)) {
            return null;
        }
        // 生成签名
        return CommUtils.hmacSha256(signMessage, secretKey).toUpperCase();
    }

    /**
     * 获取授权认证信息
     *
     * @param appId     商户号
     * @param nonceStr  请求随机串
     * @param timestamp 时间戳
     * @param signature 签名值
     * @param authType  认证类型，目前为WECHATPAY2-SHA256-RSA2048
     * @return 请求头 Authorization
     */
    public static String getAuthorization(String appId, String urlSuffix, String nonceStr, String timestamp, String signature, String authType) {
        Map<String, Object> params = new HashMap<>(5);
        params.put(ConstStr.APP_ID, appId);
        params.put(ConstStr.SIGN_URL_SUFFIX, urlSuffix);
        params.put(ConstStr.NONCE_STR, nonceStr);
        params.put(ConstStr.TIMESTAMP, timestamp);
        params.put(ConstStr.SIGN_NATURE, signature);
        return authType.concat(" ").concat(CommUtils.createLinkString(params, ",", false, true));
    }

    /**
     * 验证签名
     *
     * @param buildSignMessage
     * @param signature
     * @param secretKey
     * @return
     */
    public static boolean verifySign(String buildSignMessage, String signature, String secretKey) {
        String localSign = createSign(buildSignMessage, secretKey);
        return signature.equals(localSign);
    }
}
